const state = {
  currentLevel: 'F1',
  userLocation: null,
  appVersion: '1.0.0',
  networkStatus: 'online',
  // 老年人模式设置
  isElderlyMode: false, // 老年人模式开关
  fontSize: 'normal', // 字体大小：normal, large, extra-large
  theme: 'default' // 主题：default, elderly
}

const mutations = {
  SET_CURRENT_LEVEL(state, level) {
    state.currentLevel = level
  },
  SET_USER_LOCATION(state, location) {
    state.userLocation = location
  },
  SET_NETWORK_STATUS(state, status) {
    state.networkStatus = status
  },
  SET_ELDERLY_MODE(state, isEnabled) {
    state.isElderlyMode = isEnabled
    try { uni.setStorageSync('elderlyMode', isEnabled) } catch (e) {}
  },
  SET_FONT_SIZE(state, fontSize) {
    state.fontSize = fontSize
    try { uni.setStorageSync('fontSize', fontSize) } catch (e) {}
  },
  SET_THEME(state, theme) {
    state.theme = theme
    try { uni.setStorageSync('theme', theme) } catch (e) {}
  }
}

const actions = {
  // 设置当前楼层
  setCurrentLevel({ commit }, level) {
    commit('SET_CURRENT_LEVEL', level)
  },

  // 获取用户位置
  async getUserLocation({ commit }) {
    return new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          const location = {
            latitude: res.latitude,
            longitude: res.longitude
          }
          commit('SET_USER_LOCATION', location)
          resolve(location)
        },
        fail: reject
      })
    })
  },

  // 检查网络状态
  checkNetworkStatus({ commit }) {
    uni.getNetworkType({
      success: (res) => {
        const status = res.networkType === 'none' ? 'offline' : 'online'
        commit('SET_NETWORK_STATUS', status)
      }
    })
  },

  // 初始化应用设置（老年人模式等）
  initAppSettings({ commit }) {
    const elderlyMode = uni.getStorageSync('elderlyMode') || false
    const fontSize = uni.getStorageSync('fontSize') || 'normal'
    const theme = uni.getStorageSync('theme') || 'default'

    commit('SET_ELDERLY_MODE', elderlyMode)
    commit('SET_FONT_SIZE', fontSize)
    commit('SET_THEME', theme)
  },

  // 切换老年人模式
  toggleElderlyMode({ commit, state }) {
    const newMode = !state.isElderlyMode
    commit('SET_ELDERLY_MODE', newMode)

    // 自动调整字体大小和主题
    if (newMode) {
      commit('SET_FONT_SIZE', 'large')
      commit('SET_THEME', 'elderly')
    } else {
      commit('SET_FONT_SIZE', 'normal')
      commit('SET_THEME', 'default')
    }
  }
}

const getters = {
  currentLevel: state => state.currentLevel,
  userLocation: state => state.userLocation,
  isOnline: state => state.networkStatus === 'online',
  // 老年人模式
  isElderlyMode: state => state.isElderlyMode,
  fontSize: state => state.fontSize,
  theme: state => state.theme
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}